const globalFunctions = {
  /**
   * @name 数组扁平化+排序
   * @param {*} 
   */
  arrayFlattening: async function({array=[],asc=true}){
    let goal=[]
    await Arr(array)
    await console.log([...new Set(goal)].sort((a,b)=>{
      return asc?(a-b):(b-a)
    }));
  
    function Arr(array){
      array.forEach(ele => {
        Array.isArray(ele)?Arr(ele):(goal.push(ele))
      });
    }
  },
  /**
   * @name 使用a标签下载文件
   */
  download(fileContent,fileName){
    let str = '';
      for(var i = 1;i<5;i++){
        str+=`
          .ml${i*5}{
            margin-left:${i*5}px
          }
          .mt${i*5}{
            margin-top:${i*5}px
          }
          .mr${i*5}{
            margin-right:${i*5}px
          }
          .mb${i*5}{
            margin-bottom:${i*5}px
          }
        `
      };
      for(var i =1;i<7;i++){
        str+=`
          .fs${10+i*2}{
            font-size:${10+i*2}px;
          }
        `
      };
      let fileContent = fileContent || str;
      let data = new Blob([fileContent]);

      let href = window.URL.createObjectURL(data);
      let a = document.createElement('a');
      a.download=fileName||"test.css";
      a.href=href;
      a.click();
  },
  
  /**
   * @name 倒计时
   * @param {*} second 秒
   * @param {function} callback 
   * @description 通用
   */
  countDown(second,callback){
    var timeDown = setInterval(()=>{
      if(second===0){
        clearInterval(timeDown);
        if(callback)callback()
      }
      second--;
    },1000)
  },

  /**
   * @name 获取len长度的随机字符串
   * @param {*} len 
   */
  getRandowString(len=10){
    let chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    return new Array(len).fill("").map(val=>chars.charAt(Math.floor(Math.random() * chars.length))).join("")
  },

  /**
   * @name 获取路由
   * @param {*} vue 
   * @description 通用
   */
  getRouterPath(vue) {
    return vue.$router.history.current.path;
  },

  /**
   * @name 获取路参数
   * @param {*} vue 
   * @description 通用
   */
  getRouterParams(vue) {
    return vue.$router.history.current.params;
  },

  /**
   * @name 封装的post请求
   * @param {string} url
   * @param {obj} params 
   * @description 通用
   */
  async apiPost(url,params){
    if(window._axios)throw new Error("没有定义 _axios");
    if(window.qs)throw new Error("没有定义 qs");
    let result = null;
    try {
      await _axios.post(PATH+url,qs.stringify(params)).then(res=>result=res);
    }
    catch(err){
      throw new Error(err);
    }
    return await result?result.data:null;
  },

  /**
   * @name 调用方法序列
   * @param {*} array 
   * @description 通用
   */
  async orderMethods(array = []) {
    for (var i = 0; i < array.length; i++) {
      await array[i]();
    }
  },

  /**
   * @name 信息提示
   * @param {*} setting 基础配置信息
   * @description 通用
   */
  toMessage(setting={status:0,msg:"成功"}){
    if(!window.Element)console.warn("没有引入element；提示信息的ui使用 vant");
    if(!window._bus)throw new Error('没有定义总线 _bus ');
    const msgType = window.msgType||(window.Element?"element":"vant");
    let type = ["success","warning","error"][setting.status];
    let message = setting.msg;
    switch(msgType){
      case "element":window._bus.$message({type,message});break;
      case "vant": window._bus.$toast[setting.status==0?"success":"fail"](message);break;
    }
  },

  /**
   * @name 设置全屏
   * @param {string} id 必填
   * @param {*} vue 必填
   * @param {function} callback 
   * @description 通用
   */
  setFullScreen(id,vue,callback){
    if(!id)throw new Error("全屏元素的id必填");
    if(vue.isFullScreen===undefined)throw new Error("当前组件并没有设置全屏字段--isFullScreen");
    let fullarea = document.getElementById(id);
    if(vue.isFullScreen){
      if (document.exitFullscreen) {
        document.exitFullscreen();
      } else if (document.webkitCancelFullScreen) {
        document.webkitCancelFullScreen();
      } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
      } else if (document.msExitFullscreen) {
        document.msExitFullscreen();
      }
    }else{
      if (fullarea.requestFullscreen) {
        fullarea.requestFullscreen();
      } else if (fullarea.webkitRequestFullScreen) {
        fullarea.webkitRequestFullScreen();
      } else if (fullarea.mozRequestFullScreen) {
        fullarea.mozRequestFullScreen();
      } else if (fullarea.msRequestFullscreen) {
        fullarea.msRequestFullscreen();
      }
    }
    if(callback)callback();
    vue.$set(vue,'isFullScreen',!vue.isFullScreen)
  },

  /**
   * @name 获取压缩后的图片
   * @param {string} img 地址
   * @param {function} callback 
   * @param {} size 压缩后的尺寸
   * @description 通用
   */
  getLittleImg(img,callback,size={width:500,height:500}){
    let file = img;
    var that=this;
    let reader = new FileReader();
    let imgFile;
    reader.onload = function(e){
      imgFile = e.target.result;
      var img = new Image();
      var canvas = document.createElement("canvas");
      var context = canvas.getContext('2d');
      img.src = imgFile;

      img.onload=function(){
        let originalW = this.width;
        let originalH = this.height;
        let maxW = size.width;
        let maxH = size.height;
        let targetW = originalW ;
        let targetH=originalH;
        if(originalW>maxW||originalH>maxH){
          if(originalW / originalH > maxW / maxH){
            targetW = maxW;
            targetH = Math.round(maxW * (originalH / originalW));
          }else{
            targetH = maxH;
            targetW = Math.round(maxH * (originalW / originalH));
          }
        }
        canvas.width = targetW;
        canvas.height = targetH;
        context.clearRect(0, 0, targetW, targetH);
        var orient = that.getPhotoOrientation(img);
        if(orient===6){
          context.save();
          context.translate(targetW / 2, targetH / 2);
          context.rotate(90 * Math.PI / 180);
          context.drawImage(img, - targetH / 2, - targetW / 2, targetH, targetW);
          context.restore();
        }else{
          context.drawImage(img, 0, 0, targetW, targetH);
        }
        var final = canvas.toDataURL("image/jpeg");
        if(callback)callback(that.dataUrltoFile(final));
      }
      reader.readAsDataURL(file);
    }
  },

  /**
   * @name 获取图片旋转信息
   * @param {*} img 
   * @description 通用
   */
  getPhotoOrientation(img){
    if(!EXIF)console.error("确认已经引入exif.js");
    let orient;
    EXIF.getData(img, function () {
      orient = EXIF.getTag(this, "Orientation");
    });
    return orient;
  },

  /**
   * @name 将图片地址转换为文件
   * @param {*} url 
   * @param {*} filename 
   * @description 通用
   */
  dataUrltoFile(url,filename="file"){
    let arr = dataurl.split(',');
    let mime = arr[0].match(/:(.*?);/)[1];
    let suffix = mime.split('/')[1];
    let bstr = atob(arr[1]);
    let n = bstr.length;
    let u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], `${filename}.${suffix}`, { type: mime });
  },

  /**
   * @name a标签特性用法
   * @param {*} params 
   */
  aTagFeature(params={type:null,val:null}){
    let url = null;
    switch(params.type){
      case "tel" : url=`tel:${params.val}`;break;
      case "email": url=`emailTo:${params.val}`;break;
    }
    location.href=url;
  },

  /**
   * @name 检测参数
   * @param {*} model 数据模板 (checked,key)
   * @param {*} params 待检测的参数 
   * @description 表单
   */
  checkParams(model=null,params=null){
    if(!model)throw new Error('数据模板不能为空');
    if(!params)throw new Error('检查的数据不能为空');
    let result=false;
    model.forEach(ele=>{
      if(ele.checked&&!params[ele.key]){
        result = true;
      }
    })
    return result;
  }
}

export default globalFunctions